﻿#requires -version 3
[CmdletBinding()]
param (
    [ValidateSet('CurrentUser', 'AllUsers')]
    [string]
    $Scope = 'CurrentUser',

    [switch]
    $SkipProfile
)

$script:ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest

$PSScriptRoot = $MyInvocation.MyCommand.Path | Split-Path

$AddScriptName = 'Add-EmpanadaAddOnTool.ps1'
$InstallDestName = 'PSIseTfsAddOn'
$InstallSource = $PSScriptRoot
$ExpectedFileNames = 'Empanada.dll', $AddScriptName

$InstallSource = "$PSScriptRoot\bin\debug" ## debugging

$ExpectedFilePaths = $ExpectedFileNames |
    ForEach-Object {
        Join-Path -Path $InstallSource -ChildPath $_
    }

$ExpectedFilePaths |
    ForEach-Object {
        if (-not (Test-Path -Path $_ -PathType Leaf)) {
            throw "Expected file '$_' is missing. Installation failed."
        }
    }



$ProfileRoot = $Profile.CurrentUserCurrentHost | Split-Path
$InstallDestination = Join-Path -Path $ProfileRoot -ChildPath $InstallDestName
if ($Scope -eq 'AllUsers') {
    $InstallBase = [Environment]::GetFolderPath('ProgramFiles')
    if ([Environment]::Is64BitProcess) {
        $InstallBase = [Environment]::GetFolderPath('ProgramFilesX86') # both architectures can access this path
    }
    $InstallDestination = Join-Path -Path $InstallBase -ChildPath $InstallDestName
}

if (-not (Test-Path -Path $InstallDestination -PathType Container)) {
    New-Item -Path $InstallDestination -ItemType Container | Out-Null 
}

$ExpectedFilePaths | 
    Copy-Item -Destination $InstallDestination -Force # ShouldProcess bug??
    #todo handle file locks

"Files installed to '$InstallDestination'."
if ($SkipProfile) { return }

if ((Get-Host).Name -ne 'Windows PowerShell ISE Host') {
    throw 'Installer must be run from within the PowerShell ISE to update the profile'
}

$InstallProfile = $Profile.CurrentUserCurrentHost
if ($Scope -eq 'AllUsers') {
    $InstallProfile = $Profile.AllUsersCurrentHost
}
if (Test-Path -Path $InstallProfile -PathType Leaf) {
    $Signature = Get-AuthenticodeSignature -FilePath $InstallProfile
    if ($Signature.Status -eq 'Valid') {
        throw "Installer does not support signed profiles '$InstallProfile'."
    }
}

$PSScriptName = $MyInvocation.MyCommand.Name
$AddScriptDestPath = Join-Path -Path $InstallDestination -ChildPath $AddScriptName
(Get-Content -Path $InstallProfile) |
    ForEach-Object -Begin {
        $LineToInsert = "& '$AddScriptDestPath' # Added by $PSScriptName"
    } -Process {
        if ($_ -eq $LineToInsert) {
            $_
            $LineToInsert = $null
        } elseif ($_ -match '^[^#]*{0}' -f [Regex]::Escape($AddScriptName)) {
            "# Removed by $PSScriptName`: $_"
            if ($LineToInsert) { 
                $LineToInsert
                $LineToInsert = $null
            }
        } else {
            $_
        }
    } -End {
        if ($LineToInsert) { 
            $LineToInsert
        }
    } |
    Set-Content -Path $InstallProfile
